package com.snap.vseries.fragment.cit;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;

import com.snap.vseries.R;
import com.snap.vseries.base.CitFragment;
import com.snap.vseries.bean.TestItem;
import com.snap.vseries.dialog.NumberInputDialog;
import com.snap.vseries.framework.MoleExecutor;
import com.snap.vseries.framework.MoleTask;
import com.snap.vseries.serial.Cmd;
import com.snap.vseries.ui.widget.TextButton;
import com.snap.vseries.utils.ToastUtils;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.concurrent.Future;

import butterknife.BindView;

import static com.snap.vseries.AppConfig.DEVICE_TYPE;
import static com.snap.vseries.AppConfig.LIGHTING_MODULE_INDEX;


@SuppressLint("ValidFragment")
public class LightCommFragment extends CitFragment {

    private static final int DEFAULT_COUNT = 100;
    private static final float DEFAULT_PASS = 0.95f;
    private final int position;
    @BindView(R.id.count_et)
    TextView countEt;
    @BindView(R.id.result_label)
    TextView resultLabel;
    @BindView(R.id.result_tv)
    TextView resultTv;
    @BindView(R.id.start_btn)
    TextButton startBtn;
    private TestItem testItem;
    private DecimalFormat mFormat = new DecimalFormat("##.##%");
    private int count = DEFAULT_COUNT;
    private Future future;
    private long cancelClickTime;
    private long startTime;

    public LightCommFragment(int position, TestItem testItem) {
        this.position = position;
        this.testItem = testItem;
    }

    @Override
    protected int layoutResId() {
        return R.layout.fragment_cit_light_comm;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        countEt.setText(String.valueOf(count));
        countEt.setOnClickListener(v ->
                new NumberInputDialog().setParam(0, 1, count, 999, "循环次数", "", value -> {
                    count = (int) value;
                    countEt.setText(String.valueOf(count));
                }).show(getChildFragmentManager(), ""));
        startBtn.setOnClickListener(v -> {
            if (!isTesting()) {
                setTesing(true);
                startBtn.setText("测试中...(双击取消测试)");
                startBtn.setBackgroundResource(R.drawable.btn_cit_running);
                resultLabel.setVisibility(View.GONE);
                resultTv.setText("");
                startTime = System.currentTimeMillis();
                future = MoleExecutor.getInstance().execute(new MoleTask<Integer>() {
                    @Override
                    public Integer runInBackground() throws InterruptedException {
                        int hitCount = 0;
                        try {
                            getSerialPortHelper().open();
                            for (int i = 0; i < count; i++) {
                                Bundle bundle = getSerialPortHelper().executeWithoutRetry(Cmd.getLightingState(DEVICE_TYPE, LIGHTING_MODULE_INDEX));
                                if (bundle.getBoolean("suc")) {
                                    hitCount++;
                                }
                            }
                            return hitCount;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return hitCount;
                        } finally {
                            getSerialPortHelper().close();
                        }
                    }

                    @Override
                    public void onCompleted(Integer result) {
                        float percentage = (float) result / count;
                        String percentageStr = mFormat.format(percentage);
                        String defPassStr = mFormat.format(DEFAULT_PASS);
                        long timeCost = System.currentTimeMillis() - startTime;
                        String comment = String.format("成功次数：%d\n成功率：%s\n耗时：%s 毫秒\n平均每条耗时：%s 毫秒\n通过条件：成功率高于 %s", result, percentageStr, timeCost, timeCost / count, defPassStr);
                        testItem.setComment(comment);
                        if (percentage >= DEFAULT_PASS) {
                            testItem.setState(1);
                        } else {
                            testItem.setState(2);
                        }
                        setTesing(false);
                        startBtn.setText("开始测试");
                        startBtn.setBackgroundResource(R.drawable.btn_cit_start);
                        resultLabel.setVisibility(View.VISIBLE);
                        resultLabel.setBackgroundResource(testItem.getState() == 2 ? R.drawable.bg_red_4 : R.drawable.bg_blue6_4);
                        resultTv.setText(comment);
                        notifyItem(position);
                    }
                });
            } else {
                if ((System.currentTimeMillis() - cancelClickTime) > 2000) {
                    cancelClickTime = System.currentTimeMillis();
                } else {
                    if (future != null) future.cancel(true);
                    ToastUtils.get().showText("已取消！");
                    setTesing(false);
                    startBtn.setText("开始测试");
                    startBtn.setBackgroundResource(R.drawable.btn_cit_start);
                    resultLabel.setVisibility(View.GONE);
                    resultTv.setText("");

                    testItem.setState(0);
                    testItem.setComment("");
                    notifyItem(position);
                }
            }
        });
    }
}